package yoyu.downloader;

import android.content.Context;
import android.net.TrafficStats;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    /** 显示下载进度TextView */
    private TextView mMessageView;
    /** 显示下载进度ProgressBar */
    private ProgressBar mProgressbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.download_btn).setOnClickListener(this);
        mMessageView = (TextView) findViewById(R.id.download_message);
        mProgressbar = (ProgressBar) findViewById(R.id.download_progress);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.download_btn) {
            doDownload();
        }
    }

    /**
     * 使用Handler更新UI界面信息
     */
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {


            double temp = ((double) msg.getData().getLong("size")
                    / 5115260928L);

            int progress = (int) (temp*100);
            mProgressbar.setProgress(progress);

            if (progress == 100) {
                Toast.makeText(MainActivity.this, "下载完成！", Toast.LENGTH_LONG).show();
            }
            mMessageView.setText("下载进度:" + progress + " %   下载速度   "+(mSpeed));

        }
    };

    /**
     * 下载准备工作，获取SD卡路径、开启线程
     */
    private void doDownload() {
        // 获取SD卡路径
        String path = Environment.getExternalStorageDirectory()
                + "/amosdownload/";
        File file = new File(path);
        // 如果SD卡目录不存在创建
        if (!file.exists()) {
            file.mkdir();
        }
        // 设置progressBar初始化
        mProgressbar.setProgress(0);

        // 简单起见，我先把URL和文件名称写死，其实这些都可以通过HttpHeader获取到
//        String downloadUrl = "http://116.224.87.17/pad-download-cdn.putaocdn.com/pad_apk/010001_2.apk?app_id=363&user_id=6012788&time=1475908453&sign=ec44d795dce46f09402d7ffdaa200c70&wsiphost=local";
        String fileName = "x.iso";
        String downloadUrl = "http://10.1.223.160/test/cn.iso";
        int threadNum = 10;
        String filepath = path + fileName;
        Log.d(TAG, "download file  path:" + filepath);
        downloadTask task = new downloadTask(downloadUrl, threadNum, filepath);
        task.start();
    }

    /**
     * 多线程文件下载
     *
     * @author yangxiaolong
     * @2014-8-7
     */
    class downloadTask extends Thread {
        private String downloadUrl;// 下载链接地址
        private int threadNum;// 开启的线程数
        private String filePath;// 保存文件路径地址
        private long blockSize;// 每一个线程的下载量

        public downloadTask(String downloadUrl, int threadNum, String fileptah) {
            this.downloadUrl = downloadUrl;
            this.threadNum = threadNum;
            this.filePath = fileptah;
        }

        @Override
        public void run() {

            FileDownloadThread[] threads = new FileDownloadThread[threadNum];
            try {
                URL url = new URL(downloadUrl);
                Log.d(TAG, "download file http path:" + downloadUrl);
                URLConnection conn = url.openConnection();
                // 读取下载文件总大小
//                int fileSize = conn.getContentLength();
//                if (fileSize <= 0) {
//                    System.out.println("读取文件失败");
//                    return;
//                }
                long fileSize =  2599266496L;
                // 设置ProgressBar最大的长度为文件Size
                mProgressbar.setMax(100);

                // 计算每条线程下载的数据长度
                blockSize = (fileSize % threadNum) == 0 ? fileSize / threadNum
                        : fileSize / threadNum + 1;

                Log.d(TAG, "fileSize:" + fileSize + "  blockSize:");

                File file = new File(filePath);
                for (int i = 0; i < threads.length; i++) {
                    // 启动线程，分别下载每个线程需要下载的部分
                    threads[i] = new FileDownloadThread(url, file, blockSize,
                            (i + 1),fileSize);
                    threads[i].setName("Thread:" + i);
                    threads[i].start();
                }

                boolean isfinished = false;
                int downloadedAllSize = 0;
                while (!isfinished) {
                    isfinished = true;
                    // 当前所有线程下载总量
                    downloadedAllSize = 0;
                    for (int i = 0; i < threads.length; i++) {
                        downloadedAllSize += threads[i].getDownloadLength();
                        if (!threads[i].isCompleted()) {
                            isfinished = false;
                        }
                    }
                    // 通知handler去更新视图组件
                    Message msg = new Message();
                    msg.getData().putLong("size", downloadedAllSize);
                    mHandler.sendMessage(msg);
                    update(downloadedAllSize);
                    // Log.d(TAG, "current downloadSize:" + downloadedAllSize);
                    Thread.sleep(1000);// 休息1秒后再读取下载进度
                }
                Log.d(TAG, " all of downloadSize:" + downloadedAllSize);

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
    private int mMinIntervalUpdateSpeed = 1;
    private long mLastRefreshTime;
    private long mLastRefreshSofarBytes;
    private long mStartSofarBytes;
    private long mStartTime;
    // KB/s
    private int mSpeed;

    public void update(long sofarBytes) {
        if (mMinIntervalUpdateSpeed <= 0) {
            return;
        }

        boolean isUpdateData = false;
        do {
            if (mLastRefreshTime == 0) {
                isUpdateData = true;
                break;
            }

            long interval = SystemClock.uptimeMillis() - mLastRefreshTime;
            if (interval >= mMinIntervalUpdateSpeed || (mSpeed == 0 && interval > 0)) {
                mSpeed = (int) ((sofarBytes - mLastRefreshSofarBytes) / interval);
                mSpeed = Math.max(0, mSpeed);
                isUpdateData = true;
                break;
            }
        } while (false);

        if (isUpdateData) {
            mLastRefreshSofarBytes = sofarBytes;
            mLastRefreshTime = SystemClock.uptimeMillis();
        }

    }

    public static String getNetSpeed(Context context) {

        long nowTotalRxBytes = getTotalRxBytes(context);
        long nowTimeStamp = System.currentTimeMillis();
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换

        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;

        return String.valueOf(speed) + " kb/s";

    }

    private static long lastTotalRxBytes = 0;
    private static long lastTimeStamp = 0;

    private static long getTotalRxBytes(Context context) {
        return TrafficStats.getUidRxBytes(context.getApplicationInfo().uid)==TrafficStats.UNSUPPORTED ?
                0 :(TrafficStats.getTotalRxBytes()/1024);//转为KB
    }

}

